<?php
use think\Log;
use excel\Xlsx;

/**
 * 判断返回结果
 * @param array $result 执行结果数据
 * @param int $type log类型
 * @param string $businessSn 单据号
 * @param string $content log信息
 */
if(!function_exists('responseJson')) {
    function responseJson($code = 200, $msg = '成功', $data = []) {
        $header = [
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Accept, User',
            'Access-Control-Allow-Methods' => 'GET, POST, PUT,DELETE',
        ];
        $response = [];
        if($code == 200){
            $response['code'] = 200;
            $response['msg'] = $msg;
            $response['data'] = $data;
        } else {
            $response['code'] = $code;
            $response['msg'] = $msg;
            $response['data'] = $data;
        }
        exit(json($response)->header($header)->send());
    }
}

/**
 * @param int $code 提示信息编码
 * 错误返回
 */
if(!function_exists('errorJson')) {
    function errorJson($message = '', $code = 400) {
        responseJson($code, $message);
    }
}

/**
 * @param int $code 提示信息编码
 * @param array $data
 * 成功返回
 */
if(!function_exists('successJson')) {
    function successJson($data = [], $message = '成功') {
        responseJson(200, $message, $data);
    }
}

/**
 * 记录日志
 */
if(!function_exists('saveLog')) {
    function saveLog($message = '') {
        Log::info($message);
    }
}

/**
 * 生成excel
 * $site 'column' => 'username', 'title' => '名称'
 */
if(!function_exists('createExcel')) {
    function createExcel($site = [], $data = [], $fileName = '') {
        $excelData = [];
        $title = [];
        //设置第一行栏目名称
        foreach($site as $value){
            $title[$value['title']] = 'string';
        }
        //data
        foreach((array)$data as $key => $value) {
            foreach($site as $v){
                $excelData[$key][$v['column']] = $value[$v['column']];
            }
        }

        $writerClass = new Xlsx();
        $fileName = iconv('utf-8','gb2312', $fileName. 'xlsx'); //设置文件名
        $writerClass->writeSheet($excelData, 'Sheet1', $title);
        $writerClass->Tofile($fileName);//下载
        $writerClass->writeToStdOut();
        exit();
    }
}

/**
 * 生成csv
 * $site 'title' => '名称'
 */
if(!function_exists('createCsv')) {
    function createCsv($site = [], $data = [], $file_name = ''){
        $string = "";
        foreach ($site as $value){
            $tmp[] = iconv('utf-8', 'gb2312', $value['title']);
        }
        $string .= implode(",", $tmp)."\n"; //用英文逗号分开
        foreach ($data as $value)
        {
            $tmp = [];
            foreach ($site as $v)
            {
                $tmp[] = '"'.iconv('utf-8','gbk', $value[$v['column']]).'"'."\t";
            }
            $string .= implode(",",$tmp)."\n"; //用英文逗号分开
        }
        $filename = iconv('utf-8','gb2312', $file_name). '.csv'; //设置文件名
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo $string;
        exit();
    }
}

/**
 * curl请求
 */
if (!function_exists('curlRequest')){
    /**
     * Curl 请求函数(支持GET和POST方式)
     * @author chenyang
     * @param  string  $url     【请求的url】
     * @param  array   $data    【请求传递的数据】
     * @param  string  $method  【请求方式:GET|POST,默认GET】
     * @param  array   $header  【请求要携带的header头】
     * @param  integer $timeout 【请求超时时间】
     * @return array
     * Date Time：2020年1月15日16:42:07
     */
    function curlRequest($url, $data = [], $method = 'GET', $header = [], $timeout = 600){
        $res = [];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            // 当需要通过curl_getinfo来获取发出请求的header信息时,该选项需要设置为true
            curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        switch (strtoupper($method)) {
            case 'GET':
                if (!empty($data)) {
                    $url = $url.'?'.http_build_query($data);
                }
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
                break;
            case 'POST':
                if (class_exists('\CURLFile')) {
                    curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
                }elseif (defined('CURLOPT_SAFE_UPLOAD')) {
                    curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
                }
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                break;
        }
        $result = curl_exec($ch);

        // 关闭会话
        curl_close($ch);

        return $result;
    }
}

/**
 * 去掉html带出的一些空格换行
 */
if(!function_exists('DeleteHtml')){
    function DeleteHtml($str)
    {
        $str = preg_replace("/\t/","",$str); //使用正则表达式替换内容，如：空格，换行，并将替换为空。
        $str = preg_replace("/\r\n/","",$str);
        $str = preg_replace("/\r/","",$str);
        $str = preg_replace("/\n/","",$str);

        $str = rtrim($str); //清除字符串两边的空格
        $str = ltrim($str); //清除字符串两边的空格
        return  trim($str); //返回字符串
    }
}


